import matplotlib.pyplot as plt
import matplotlib.patches as patches
import numpy as np


#使用matplotlib怎样修改折线图的背景为红黄蓝三段区域并在折线背景添加小方格


# 创建一些示例数据用于折线图
x = np.linspace(0, 10, 100)
y = np.sin(x)

# 创建一个新的图表和轴
fig, ax = plt.subplots()

# 绘制折线图
ax.plot(x, y)

# 设置背景颜色为红黄蓝三段（这部分代码保持不变）
segment_positions = [0, 3, 6, 10]
ax.add_patch(patches.Rectangle((segment_positions[0], ax.get_ylim()[0]), segment_positions[1]-segment_positions[0], ax.get_ylim()[1]-ax.get_ylim()[0], facecolor='red', zorder=-1))
ax.add_patch(patches.Rectangle((segment_positions[1], ax.get_ylim()[0]), segment_positions[2]-segment_positions[1], ax.get_ylim()[1]-ax.get_ylim()[0], facecolor='yellow', zorder=-1))
ax.add_patch(patches.Rectangle((segment_positions[2], ax.get_ylim()[0]), segment_positions[3]-segment_positions[2], ax.get_ylim()[1]-ax.get_ylim()[0], facecolor='blue', zorder=-1))

# 添加网格线
# 这里设置为两者都显示，你可以根据需要调整which参数来只显示主网格线或次网格线
ax.grid(which='both', color='gray', linestyle='--', linewidth=0.5, alpha=0.5, zorder=-2)

# 设置轴的界限以确保背景完全可见
ax.set_xlim(segment_positions[0], segment_positions[3])
ax.set_ylim(-1.2, 1.2)  # 根据你的数据调整y轴范围

# 显示图表
plt.show()